package com.aceleeyy.apb.base;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * 服务者-基础控制器
 *
 * @author Ace Lee
 * @version 1.0
 * @date 2020/8/10 10:34
 **/
public abstract class BaseController<T extends BaseModel> {

    @Autowired
    private IBaseService<T> baseService;

    /**
     * 列表
     *
     * @return
     */
    @GetMapping("")
    public Object getList( @RequestParam(value = "isPage", required = false) Boolean isPage,
                           @RequestParam(value = "attributes", required = false) String attributes,
                           @RequestParam(value = "filters", required = false) String filters,
                           @RequestParam(value = "orders", required = false) String orders,
                           @RequestParam(value = "skip", required = false) Integer skip,
                           @RequestParam(value = "top", required = false) Integer top) {
        return baseService.list(isPage,attributes,filters,orders,skip,top);
    }


    /**
     * 查看
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public T getOne(@PathVariable Long id){
        return (T)baseService.getById(id);
    }

    /**
     * 新增
     *
     * @param entity
     * @return
     */
    @Transactional
    @PostMapping("")
    public boolean addOne(@RequestBody T entity){
        entity.setCreateTime(new Date());
        entity.setCreator(0L);
        entity.setIsDeleted(false);
        //新增前置处理
        beforeAdd(entity);
        return baseService.save(entity);
    }

    private void beforeAdd(T entity) {

    }

    /**
     * 修改
     *
     * @param id
     * @param entity
     * @return
     */
    @Transactional
    @PutMapping("/{id}")
    public boolean editOne(@PathVariable Long id,@RequestBody T entity){
        entity.setId(id);
        entity.setModifyTime(new Date());
        entity.setModifier(0L);
        //修改前置处理
        beforeEdit(entity);
        return baseService.updateById(entity);
    }

    private void beforeEdit(T entity) {

    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Transactional
    @DeleteMapping("/{id}")
    public boolean delOne(@PathVariable Long id){
        //删除前置处理
        beforeDel(id);
        return baseService.removeById(id);
    }

    private void beforeDel(Long id) {

    }
}
